<?php 

class Config extends ConfigAppModel
{
	var $name = 'Config';
	var $useTable = false;
	
	/**
	 * Saves the configuration file.
	 * 
	 * $configs Configuration array
	 * $file Configuration file where above array is stored
	 * $importDb Trigger to import database (Useful while installation)
	 * $tables Tells importer to import only specified tables when not empty. Works only with schema files
	 * $mergeOld Whether old values should me merged with present value or put content directly
	 */
	function save($configs, $file=CONFIG_FILE, $importDb = false, $tables = array(),$mergeOld = true)
	{
		// consider existing config too
		if(file_exists($file) && $mergeOld == true)
		{
			include($file); // get $config from requested file
			$configs = Set::merge($config, $configs);
		}
				
		$content = '<?php'."\n\n";
		//prd($configs);
		foreach($configs as $type=>$config)
		{
			if(!is_array($config))
			{
				continue;	
			}
			foreach ($config as $key => $value) {
				//pr($key);
				$content .= "\$config['$type']['$key']";
	
				if (is_array($value)) {
					$content .= " = array(";
	
					foreach ($value as $key1 => $value2) {
						$value2 = addslashes($value2);
						$content .= "'$key1' => '$value2', ";
					}
					$content .= ");\n";
				} else {
					$value = addslashes($value);
					$content .= " = '$value';\n";
				}
			}
			$content .= "\n\n";
		}

		$content .= '?>';
		if(file_put_contents($file, $content))
		{
			// if instructed to import database
			if($importDb)
			{
				$dbDumpFile = Configure::read('Config.dbDump');
				if(file_exists($dbDumpFile))
				{
					$this->_importDb($dbDumpFile, $configs, $tables);
				}
			}
			return true;
		}
		return false;
	}
	
	function _importDb($dumpFile, $config, $tablesToImport)
	{
		// 1. check dump file type
		$ext = end(explode('.', $dumpFile));
		if($ext=='sql')
		{
			// connect to mysql server directly
			$link = mysql_connect($config['Database']['host'], $config['Database']['login'], $config['Database']['password']);
			mysql_select_db($config['Database']['database']);
			Utility::importSqlFile($dumpFile, true);
		}
		elseif($ext=='php')
		{
			// import app schema
			require_once(LIBS.'model'.DS.'schema.php');
			$this->Schema = new CakeSchema();
			$options = array(
				'file' => basename($dumpFile)
			);
			$this->Schema->path = dirname($dumpFile);
			$Schema = $this->Schema->load($options);
			
			// create a new db configuration
			$connectionManager = ConnectionManager::getInstance();
			$dbSettings = am($connectionManager->config->default, $config['Database']);
			ConnectionManager::create('temp', $dbSettings);
			$db = ConnectionManager::getDataSource('temp');

			if(!is_object($db)){
				return; // if db configuration not correct, ignore the importing process
			}
			$fail = false;
			foreach ($Schema->tables as $table => $fields) 
			{
				if(!empty($tablesToImport))
				{
					if(!in_array($table, $tablesToImport))
					{
						//echo $table; exit;
						continue;
					}
				}
				try
				{
					$sql = $db->createSchema($Schema, $table);
					if(!$db->_execute($sql))
					{
						$fail = true;
						$this->log("Unable to run query:".$sql, 'installSqlError');
					}else
					{
					}
				}
				catch(Exception $e)
				{
					$this->log($e->getMessage(), 'installError');
				}
			}
			//@FIXME hack to be used by installer if inital data is false 
			if(cr("Config.NoVersionCheck") !== true)
			{
				App::import("Model","Config.AppConfig");
				$AppConfigModel = new AppConfig(array("ds"=>"temp"));
				$version = "";
				if(file_exists(ROOT.DS.'version.txt'))
				{
					$version = file_get_contents(ROOT.DS.'version.txt');
				}
				$configData = array($AppConfigModel->alias => array("version"=>$version));
				$AppConfigModel->create();
				$AppConfigModel->save($configData);
			}
			if(!$fail);
			{
				callHooks('AfterDbCreate','.+',$this,'temp');
			}
			// unset temporary connection
			/*
			unset($connectionManager->config->temp);
			unset($connectionManager->_dataSources['temp']);
			unset($connectionManager->_connectionsEnum['temp']);
			*/
			/* events execution removed for now
			foreach ($create as $table => $sql)
			{

				if (!$Schema->before(array($event => $table))) {
					return false;
				}
				try
				{
					$db->_execute($sql);
				}
				catch(Exception $e)
				{
					echo $e->getMessage();
				}
				$Schema->after(array($event => $table, 'errors'=> $errors));
				
			}*/
		}
	}
	
	/**
	 * Return config data
	 * @param $file
	 * @return unknown_type
	 */
	function get($file = CONFIG_FILE)
	{
		include(CONFIG_FILE);
		return $config;
	}
}

?>